// pages/secondhand/list/list.js
const app = getApp()

Page({
  data: {
    secondhandList: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    searchKeyword: '',
    filterType: 'all',
    secondhandTypes: []
  },

  onLoad() {
    // 检查登录状态
    if (!app.utils.checkLoginStatus()) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    // 检查是否已选择学校
    if (!app.utils.checkSchoolId()) {
      wx.reLaunch({
        url: '/pages/school-select/school-select'
      })
      return
    }

    this.loadTypes()
    this.loadSecondhandList()
  },

  // 加载商品类型
  async loadTypes() {
    try {
      const response = await app.utils.request({
        url: '/secondhand/types'
      })

      console.log('商品类型响应:', response)
      if (response && response.code === 200) {
        this.setData({
          secondhandTypes: response.data || []
        })
        console.log('商品类型列表:', response.data)
      }
    } catch (error) {
      console.error('加载类型失败:', error)
    }
  },

  onShow() {
    // 检查登录状态
    if (!app.utils.checkLoginStatus()) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    // 检查是否已选择学校
    if (!app.utils.checkSchoolId()) {
      wx.reLaunch({
        url: '/pages/school-select/school-select'
      })
      return
    }

    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }

    // 页面显示时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadMore()
    }
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      hasMore: true,
      secondhandList: []
    })
    this.loadSecondhandList()
    wx.stopPullDownRefresh()
  },

  // 加载二手商品列表
  async loadSecondhandList() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        keyword: this.data.searchKeyword
      }

      // 只在有值时才添加 typeId 参数
      if (this.data.filterType !== 'all' && this.data.filterType) {
        params.typeId = this.data.filterType
      }

      const response = await app.utils.request({
        url: '/secondhand/list',
        data: params
      })

      if (response && response.code === 200) {
        const newList = response.data.records || []
        // 处理状态文本和图片
        const processedList = newList.map(item => {
          let firstImage = ''
          // 解析图片JSON，获取第一张图片
          if (item.images) {
            try {
              const imageUrls = JSON.parse(item.images)
              if (imageUrls && imageUrls.length > 0) {
                firstImage = imageUrls[0]
              }
            } catch (e) {
              console.error('解析图片失败:', e)
            }
          }
          
          return {
            ...item,
            statusText: this.getStatusText(item.status),
            firstImage: firstImage
          }
        })
        
        const secondhandList = this.data.page === 1 ? processedList : [...this.data.secondhandList, ...processedList]
        
        this.setData({
          secondhandList,
          hasMore: newList.length === this.data.pageSize,
          loading: false
        })
      }
    } catch (error) {
      console.error('加载二手商品列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 加载更多
  loadMore() {
    this.setData({
      page: this.data.page + 1
    })
    this.loadSecondhandList()
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 执行搜索
  onSearch() {
    this.refreshData()
  },

  // 筛选类型改变
  onFilterChange(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      filterType: type
    })
    this.refreshData()
  },

  // 跳转到详情页
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/secondhand/detail/detail?id=${id}`
    })
  },

  // 跳转到发布页
  navigateToPublish() {
    wx.navigateTo({
      url: '/pages/secondhand/publish/publish'
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'on_sale': '在售',
      'sold': '已售',
      'off_shelf': '已下架'
    }
    return statusMap[status] || '未知状态'
  }
})
